# -*- coding = utf-8 -*-
# @time:2022-03-16 17:41
# Author:henry_oulen@163.com
# @File:change_wallper.py
# @Software:PyCharm


import random
import time
import requests
from bs4 import BeautifulSoup
import os
import win32api, win32con, win32gui
from tornado.ioloop import PeriodicCallback
from tornado import ioloop
import platform



file_path = r'D:\backend'

def commend_req(url):
    """
    统一调用
    :param url:
    :return:
    """

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                             'Chrome/51.0.2704.63 Safari/537.36'}
    response = requests.get(url, headers=headers)
    return response


def set_wallpaper(img_path):
    """
    更新桌面壁纸
    :param img_path:
    :return:
    """

    # 打开指定注册表路径
    reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
    # 最后的参数:2拉伸,0居中,6适应,10填充,0平铺
    win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
    # 最后的参数:1表示平铺,拉伸居中等都是0
    win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    # 刷新桌面
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, win32con.SPIF_SENDWININICHANGE)


def get_contnet(url):
    """
    获取文件进行解析
    :param url:
    :return:
    """

    _response = commend_req(url)
    soup = BeautifulSoup(_response.text, 'lxml')
    all_content = soup.find_all(class_="card progressive")
    _return = []
    for i in all_content:
        _date = i.find(class_="calendar").find(class_="t").text
        href = i.find(class_="mark").get("href")
        url = "https://bing.ioliu.cn/" + str(href).split("?")[0] + "?force=download"
        _return.append({
            "date": _date,
            "url": url
        })
    return _return


def save_file(all_url):
    """
    爬取文件进行保存
    :param all_url:
    :return:
    """
    if all_url:
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        os.chdir(file_path)
        _file = file_path + "\\" + time.strftime("%Y-%m-%d", time.localtime()) + ".jpg"
        if not os.path.exists(_file):
            for i in all_url:
                _response = commend_req(i.get("url"))
                content = _response.content
                file_name = i.get("date") + ".jpg"
                abs_path = file_path + '\\' + file_name
                with open(abs_path, 'wb') as f:
                    if os.path.exists(abs_path):
                        f.write(content)
                        print("save file %s"%file_name)


def check_file():
    try:
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        url = 'https://bing.ioliu.cn/?p=1'
        _file = file_path + "\\" + time.strftime("%Y-%m-%d", time.localtime()) + ".jpg"
        if not os.path.exists(_file):
            data = get_contnet(url)
            save_file(data)

    except Exception as e:
        pass


def change_wallpaper():
    for root, dirs, files in os.walk(file_path):
        if files:
            file = file_path + "\\" + random.choice(files)
            set_wallpaper(file)

def main():
    print("enjoy your self")
    # for root, dirs, files in os.walk(file_path):
    #     print(files)
    #     file = file_path + "\\" + random.choice(files)
    check_file()
    change_wallpaper()
    PeriodicCallback(check_file, callback_time=2 * 60 * 60 * 1000).start()  # 最后的单位是毫秒  定时任务获取壁纸
    PeriodicCallback(change_wallpaper, callback_time=2 * 60 * 60 * 1000).start()  # 最后的单位是毫秒  定时随机更新壁纸
    ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    main()
    if (platform.system() == 'Windows'):
        import win32api
        import win32gui
        ct = win32api.GetConsoleTitle()
        hd = win32gui.FindWindow(0, ct)
        win32gui.ShowWindow(hd, 0)



